<?php
/* The iPhone facade controller */
define('PHOTO_DIR', '../photos/');
require_once('../lib/diy.php');
require_once('../lib/util.php');
require_once('../lib/model.php');
require_once('../lib/diy_image.php');

/* Test Code 
print "SUCCESS";
exit;
if( !isset($_POST['service_type']) ||
    $_POST['service_type'] != 'iPhone')
  {
    die("Invalid request.");
  }
*/

/* Get address using lat/lng */
$category_id = 0; /* HOW TO Determine this? */

$input = array();
$input['subject'] = shorten_title($_POST['details']);
$email_slice = explode('@', $_POST['email']);
$input['reporter'] = $email_slice[0];
$input['email'] = $_POST['email'];
$input['details'] = $_POST['details'];
$input['lat'] = $_POST['lat'];
$input['lng'] = $_POST['lng'];
$input['service_type'] = $_POST['service_type'];

$address = simplexml_load_string(coord_to_address($input['lat'], $input['lng']));
if (!isset($_FILES['photo']))
  {
    die("No image");
  }

if ($address['name1'] == '') {
  die("Invalid Coordinate");
}

$input['address1'] = $address['name1'];
$input['address2'] = $address['name2'];
$input['address3'] = $address['name3'];
$input['address_hash'] = get_address_hash($address['name1'], $address['name2'], $address['name3']);

$input['created_time'] = get_current_time();
$input['modified_time'] = get_current_time();

$problems = new DiyModel("problems");

if (!$problems->save($input))
  die("Data upload failure");

$inserted_id = $problems->id;
if ( isset($_FILES['photo']) )
  {
    $tmp_name = $_FILES['photo']['tmp_name'];
    $image_path = PHOTO_DIR . $inserted_id;
    if (!move_uploaded_file ( $tmp_name, $image_path)) 
      die("Image upload failure");
    $diy_img = new DiyImage();
    $diy_img->makeThumbnail($image_path, $image_path . '_thumb');
  }

print "SUCCESS";
?>
